<?php
namespace App\Admin\Controllers\Consultation;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use App\Admin\Controllers\Common\Common;

class RegisterController extends Controller {
	public function index(Request $req) {
		$parent_info = DB::table('consultation_parent as p')
			->leftJoin('consultation_parent_to_st as pt','p.id','=','pt.p_id')
			->where('p.phone',$req['phone'])
			->first(['p.*','pt.relation']);
		$st_info = DB::table('consultation_st')
			->where('id',$req['st_id'])
			->first();
		$other_parents = DB::table("consultation_parent_to_st as pts")
			->leftJoin('consultation_parent as p','pts.p_id','=','p.id')
			->where([
				['pts.st_id','=',$req['st_id']],
				['pts.is_primary','=',0]
			])->get(['p.*','pts.relation']);
		$work_orders = DB::table('consultation_workorder')
			->where('st_id',$req['st_id'])
			->get();

		$parent_info = json_decode(json_encode($parent_info),true);
		$st_info = json_decode(json_encode($st_info),true);
		$other_parents = json_decode(json_encode($other_parents),true);
		$work_orders = json_decode(json_encode($work_orders),true);

		if(empty($parent_info)) {
			$parent_info = [
				'id' => "",
				'phone' => $req['phone'],
				'name' => "",
				'relation' => "",
				'id_card' => "",
			];
		}
		if(empty($st_info)){
			$st_info = [
				"id" => "",
				"enroll_at" => "",
				"name" => "",
				"sex" => "",
				"step" => '初始',
				"birthday" => "",
				"school_info" => '{"stage":"0","grade":"","city":"","district":"","school":"","special":"0"}',
				'lvl_log' => '初始定级A',
				'level' => "A"
			];
		}
		return view("admin.consultation.st.register",[
			"ParentInfo" => $parent_info,
			"StInfo" => $st_info,
			"OtherParents" => $other_parents,
			"WorkOrders" => $work_orders
		]);
	}

	/**
	 * [insert or update]
	 */
	public function save(Request $r) {
		DB::beginTransaction();
		try {
			// 家长表
			$dataInP = [
				'id' => $r['p']['id'],
				'name' => $r['p']['name'],
				'phone' => $r['p']['phone'],
				'id_card' => $r['p']['id_card']
			];
			if($dataInP['id']){
				DB::table('consultation_parent')
				->where('id',$dataInP['id'])
				->update($dataInP);
			}else{
				$dataInP['id'] = DB::table('consultation_parent')
					->insertGetId($dataInP);
			}
			$lvl_changed = "未更改";
			// 学生表
			$dataInSt = [
				'id' => $r['st']['id'],
				'enroll_at' => $r['st']['enroll_at'],
				'name' => $r['st']['name'],
				'sex' => $r['st']['sex'],
				'birthday' => $r['st']['birthday'],
				'school_info' => json_encode($r['st']['school_info']),
				'lvl_log' => implode(",",$r['st']['lvl_log']),
				'level' => $r['o']['level']
			];
			switch ($r['o']['ask_type']) {
				case '试听记录':
					$dataInSt['step'] = "试听";
					break;
				case '报名':
					$dataInSt['step'] = "报名";
					break;
				case '二报记录':
					$dataInSt['step'] = "二报";
					break;
				case '新班家长会记录':
					$dataInSt['step'] = "新班家长会";
					break;
			}
			if($dataInSt['id']){
				$lvl = DB::table('consultation_st')
					->where('id',$dataInSt['id'])
					->value('level');
				if($lvl != $dataInSt['level']){
					$lvl_changed = $lvl."-".$dataInSt['level'];
				}
				DB::table('consultation_st')
				->where('id',$dataInSt['id'])
				->update($dataInSt);
			}else{
				$dataInSt['primary_parent_id'] = $dataInP['id'];
				$dataInSt['primary_parent_name'] = $dataInP['name'];
				$dataInSt['primary_phone'] = $dataInP['phone'];
				$dataInSt['id'] = DB::table('consultation_st')
					->insertGetId($dataInSt);
			}
			// 关联表
			DB::table('consultation_parent_to_st')->updateOrInsert([
					'relation' => $r['p']['relation'],
					'p_id' => $dataInP['id'],
					'st_id' => $dataInSt['id'],
					'is_primary' => 1
				],[
					'p_id' => $dataInP['id'],
					'st_id' => $dataInSt['id']
			]);
			// 咨询记录表
			$dataInList = [
				'admin_id' => Admin::user()->id,
				'admin_name' => Admin::user()->username,
				'remark' => $r['o']['remark'],
				'type' => $r['o']['ask_type'],
				'status' => "无",
				'ask_at' => date("Y-m-d H:i:s"),
				'st_id' => $dataInSt['id']
			];
			DB::table('consultation_list')->insert($dataInList);
			// 工单表
			$dataInO = [
				'st_id' => $dataInSt['id'],
				'ask_way' => $r['o']['ask_way'],
				'ask_type' => $r['o']['ask_type'],
				'ask_type_s' => $r['o']['ask_type_s'],
				'phone' => $dataInP['phone'],
				'relation' => $r['p']['relation'],
				'level' => $r['st']['level'],
				'level_changed' => $lvl_changed,
				'expect_revisit' => $r['o']['expect_revisit'],
				// 'expect_revisit_at' => "",
				'remark' => $r['o']['remark'],
				'admin_id' => Admin::user()->id,
				'admin_name' => Admin::user()->username
			];
			if(isset($r['o']['attitude_opts'])){
				$dataInO['attitude_opts'] = implode(",",$r['o']['attitude_opts']);
			}
			DB::table("consultation_workorder")->insert($dataInO);
			DB::commit();
			return ['code'=>1,'msg'=>'保存成功','data'=>[
				'phone' => $r['p']['phone'],
				'st_id' => $dataInSt['id']
			]];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'保存失败，请稍后...'.$e->getMessage(),'data'=>''];
		}
	}

	/**
	 * [家长学生绑定]
	 */
	public function doLink(Request $r) {
		DB::beginTransaction();
		try {
			$pid = DB::table('consultation_parent')
				->where('phone','=',$r['phone'])
				->value('id');
			if(!$pid) {
				$pid = DB::table('consultation_parent')->insertGetId([
					'phone' => $r['phone'],
					'name' => $r['name'],
					'id_card' => $r['id_card']
				]);
			}
			DB::table('consultation_parent_to_st')->updateOrInsert([
				'p_id' => $pid,
				'st_id' => $r['st_id'],
				'relation' => $r['relation']
			],[
				'p_id' => $pid,
				'st_id' => $r['st_id'],
			]);
			$primary_phone = DB::table("consultation_st")
				->where('id','=',$r['st_id'])
				->value('primary_phone');
			DB::commit();
			return ['code'=>1,'msg'=>'ok','data'=>['primary_phone' => $primary_phone]];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'绑定学生失败:'.$e->getMessage(),'data'=>""];
		}
	}

	/**
	 * [编辑其他家长]
	 */
	public function editParent(Request $r) {
		DB::beginTransaction();
		try {
			DB::table('consultation_parent')
			->where('id','=',$r['id'])
			->update([
				'name' => $r['name'],
				'phone' => $r['phone'],
				'id_card' => $r['id_card']
			]);
			DB::table('consultation_parent_to_st')
			->where([
				'p_id' => $r['id'],
				'st_id' => $r['st_id']
			])->update([
				'relation' => $r['relation']
			]);
			if($r['is_primary'] == "1"){
				// 关联表
				DB::table('consultation_parent_to_st')
				->where([
					'st_id' => $r['st_id']
				])->update(['is_primary' => 0]);
				DB::table('consultation_parent_to_st')
				->where([
					'p_id' => $r['id'],
					'st_id' => $r['st_id']
				])->update(['is_primary' => 1]);
				// 学生表
				DB::table('consultation_st')
				->where('id','=',$r['st_id'])
				->update([
					'primary_phone' => $r['phone'],
					'primary_parent_id' => $r['id'],
					'primary_parent_name' => $r['name']
				]);
			}
			$primary_phone = DB::table('consultation_st')
				->where('id','=',$r['st_id'])
				->value('primary_phone');
			DB::commit();
			return ['code'=>1,'msg'=>'ok','data'=>[
				'phone' => $primary_phone,
				'st_id' => $r['st_id']
			]];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'编辑失败:'.$e->getMessage(),'data'=>""];
		}

	}
}
